﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SmartLib.Utils
{
    public abstract class ReaderWriterCache<TKey,TValue>
    {
        private readonly Dictionary<TKey, TValue> _cache;
        private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();

        protected ReaderWriterCache()
            : this(null)
        {
        }

        protected ReaderWriterCache(IEqualityComparer<TKey> comparer)
        {
            _cache = new Dictionary<TKey, TValue>(comparer);
        }

        protected Dictionary<TKey, TValue> Cache
        {
            get
            {
                return _cache;
            }
        }

        protected TValue FetchOrCreateItem(TKey key, Func<TValue> creator)
        {
            _rwLock.EnterReadLock();
            try
            {
                TValue existingEntry;
                if (_cache.TryGetValue(key, out existingEntry))
                {
                    return existingEntry;
                }
            }
            finally
            {
                _rwLock.ExitReadLock();
            }

            TValue newEntry = creator();
            _rwLock.EnterWriteLock();
            try
            {
                TValue existingEntry;
                if (_cache.TryGetValue(key, out existingEntry))
                {
                    return existingEntry;
                }

                _cache[key] = newEntry;
                return newEntry;
            }
            finally
            {
                _rwLock.ExitWriteLock();
            }
        }
    }
}
